import { User } from '@supabase/supabase-js'

// Authentication and User Types
export interface AuthContextType {
  user: User | null
  userProfile: UserProfile | null
  subscription: Subscription | null
  loading: boolean
  initializing: boolean
  signIn: (email: string, password: string, rememberMe?: boolean) => Promise<void>
  signUp: (email: string, password: string, userData?: Partial<UserProfile>) => Promise<void>
  signOut: () => Promise<void>
  resetPassword: (email: string) => Promise<void>
  updatePassword: (newPassword: string) => Promise<void>
  updateProfile: (updates: Partial<UserProfile>) => Promise<void>
  updateSubscription: (planType: SubscriptionPlan) => Promise<void>
  deleteAccount: () => Promise<void>
  refreshUserData: () => Promise<void>
}

export interface UserProfile {
  id: string
  user_id: string
  email: string
  full_name?: string
  display_name?: string
  avatar_url?: string
  subscription_status: SubscriptionStatus
  subscription_tier?: string
  subscription_start_date?: string
  subscription_end_date?: string
  paper_preferences: PaperPreferences
  notification_preferences: NotificationPreferences
  privacy_settings: PrivacySettings
  account_settings: AccountSettings
  gdpr_consent: boolean
  gdpr_consent_date?: string
  created_at: string
  updated_at: string
  last_login?: string
  is_active: boolean
  email_verified: boolean
  phone_number?: string
  phone_verified?: boolean
}

export interface PaperPreferences {
  categories: ArxivCategory[]
  keywords: string[]
  authors: string[]
  institutions: string[]
  min_publication_date?: string
  max_results_per_search?: number
  language_preferences?: string[]
  subject_areas?: string[]
}

export interface NotificationPreferences {
  email_notifications: boolean
  weekly_digest: boolean
  instant_alerts: boolean
  paper_recommendations: boolean
  new_category_papers: boolean
  author_updates: boolean
  keyword_matches: boolean
  push_notifications: boolean
  sms_notifications: boolean
  digest_frequency: 'daily' | 'weekly' | 'monthly'
  quiet_hours: {
    enabled: boolean
    start_time: string
    end_time: string
  }
}

export interface PrivacySettings {
  profile_visibility: 'public' | 'private' | 'academic'
  search_history_retention: number // days
  data_sharing_consent: boolean
  analytics_consent: boolean
  marketing_consent: boolean
  research_participation_consent: boolean
  data_export_format: 'json' | 'csv' | 'pdf'
}

export interface AccountSettings {
  two_factor_enabled: boolean
  login_alerts: boolean
  session_timeout: number // minutes
  password_strength_requirement: 'basic' | 'medium' | 'strong'
  allowed_login_methods: ('email' | 'google' | 'orcid' | 'institutional')[]
  backup_email?: string
}

export type SubscriptionStatus = 'free' | 'premium' | 'academic' | 'institutional'
export type SubscriptionPlan = SubscriptionStatus

export interface Subscription {
  id: string
  user_id: string
  plan_type: SubscriptionPlan
  status: SubscriptionStatusType
  start_date: string
  end_date?: string
  payment_method?: PaymentMethod
  payment_id?: string
  billing_cycle?: 'monthly' | 'yearly'
  features: SubscriptionFeatures
  usage_metrics: UsageMetrics
  billing_address?: BillingAddress
  tax_information?: TaxInformation
  created_at: string
  updated_at: string
}

export type SubscriptionStatusType = 'active' | 'cancelled' | 'expired' | 'pending' | 'suspended'
export type PaymentMethod = 'stripe' | 'paypal' | 'university' | 'institution' | 'invoice'

export interface SubscriptionFeatures {
  max_saved_papers: number
  max_alerts: number
  max_search_queries: number
  advanced_search: boolean
  api_access: boolean
  priority_support: boolean
  analytics: boolean
  export_capabilities: boolean
  bulk_download: boolean
  collaboration_features: boolean
  custom_categories: boolean
}

export interface UsageMetrics {
  saved_papers_count: number
  active_alerts_count: number
  monthly_searches: number
  api_requests_count: number
  storage_used_mb: number
  last_updated: string
}

export interface BillingAddress {
  name: string
  company?: string
  address_line_1: string
  address_line_2?: string
  city: string
  state: string
  postal_code: string
  country: string
}

export interface TaxInformation {
  tax_id?: string
  vat_number?: string
  tax_exempt: boolean
  billing_country: string
}

// Session and Security Types
export interface UserSession {
  id: string
  user_id: string
  session_token: string
  device_info?: DeviceInfo
  location_info?: LocationInfo
  created_at: string
  expires_at: string
  last_activity: string
  is_active: boolean
}

export interface DeviceInfo {
  device_type: 'desktop' | 'mobile' | 'tablet'
  browser: string
  operating_system: string
  user_agent: string
  screen_resolution?: string
}

export interface LocationInfo {
  ip_address: string
  country?: string
  region?: string
  city?: string
  timezone?: string
}

// Authentication Form Types
export interface LoginFormData {
  email: string
  password: string
  rememberMe: boolean
}

export interface SignUpFormData {
  email: string
  password: string
  confirmPassword: string
  fullName: string
  displayName?: string
  gdprConsent: boolean
  marketingConsent: boolean
  termsAccepted: boolean
}

export interface ResetPasswordFormData {
  email: string
}

export interface ChangePasswordFormData {
  currentPassword: string
  newPassword: string
  confirmNewPassword: string
}

export interface UpdateProfileFormData {
  full_name?: string
  display_name?: string
  avatar_url?: string
  phone_number?: string
}

// ArXiv Specific Types
export type ArxivCategory = 
  | 'cs.AI' | 'cs.CL' | 'cs.CV' | 'cs.LG' | 'cs.NE' | 'cs.RO' // Computer Science
  | 'math.AG' | 'math.AT' | 'math.CO' | 'math.DG' | 'math.GM' | 'math.GT' // Mathematics
  | 'physics.app-ph' | 'physics.atom-ph' | 'physics.comp-ph' | 'physics.data-an' // Physics
  | 'stat.AP' | 'stat.CO' | 'stat.ME' | 'stat.ML' | 'stat.TH' // Statistics
  | 'econ.EM' | 'econ.GN' | 'econ.TH' // Economics
  | 'q-bio.BM' | 'q-bio.CB' | 'q-bio.GN' | 'q-bio.MN' // Biology
  | 'q-fin.CP' | 'q-fin.EC' | 'q-fin.GN' | 'q-fin.MF' // Finance

export interface ArxivPaper {
  id: string
  arxiv_id: string
  title: string
  authors: string[]
  abstract: string
  categories: ArxivCategory[]
  published_date: string
  updated_date: string
  pdf_url: string
  doi?: string
  journal_reference?: string
  subjects: string[]
}

// API Response Types
export interface ApiResponse<T> {
  data?: T
  error?: ApiError
  success: boolean
  message?: string
  pagination?: PaginationInfo
}

export interface ApiError {
  code: string
  message: string
  details?: any
}

export interface PaginationInfo {
  current_page: number
  total_pages: number
  total_items: number
  items_per_page: number
  has_next: boolean
  has_previous: boolean
}

// UI Component Types
export interface AuthUIState {
  isLoginOpen: boolean
  isSignUpOpen: boolean
  isResetPasswordOpen: boolean
  isProfileOpen: boolean
  currentStep: number
  errors: Record<string, string>
  loading: Record<string, boolean>
}

export interface ValidationErrors {
  [key: string]: string[]
}

export interface FormFieldConfig {
  name: string
  label: string
  type: 'text' | 'email' | 'password' | 'tel' | 'url' | 'select' | 'checkbox' | 'textarea'
  required?: boolean
  placeholder?: string
  options?: { value: string; label: string }[]
  validation?: {
    minLength?: number
    maxLength?: number
    pattern?: RegExp
    custom?: (value: any) => string | null
  }
}

// Event Types
export interface AuthEvent {
  type: 'SIGN_IN' | 'SIGN_UP' | 'SIGN_OUT' | 'PASSWORD_RESET' | 'PROFILE_UPDATE' | 'SUBSCRIPTION_CHANGE'
  timestamp: string
  user_id?: string
  metadata?: Record<string, any>
}

// Permission and Role Types
export interface UserRole {
  id: string
  name: string
  permissions: Permission[]
  is_system_role: boolean
}

export interface Permission {
  id: string
  name: string
  resource: string
  action: 'create' | 'read' | 'update' | 'delete' | 'manage'
}

// Analytics Types
export interface UserAnalytics {
  user_id: string
  session_count: number
  total_session_duration: number
  papers_viewed: number
  searches_performed: number
  papers_saved: number
  last_active: string
  engagement_score: number
}